'use client';

import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Card, Tabs, Form, Button, Space } from 'antd';
import { ArrowLeftOutlined, EditOutlined, SaveOutlined } from '@ant-design/icons';
import { useRouter, useSearchParams } from 'next/navigation';
import BasicInfoForm from './components/BasicInfoForm';
import ReservationSettings from './components/ReservationSettings';
import TimeSchedule from './components/TimeSchedule';
import { instrumentApi } from '@/apis/instrument';
import { InstrumentInfo, InstrumentCreateRequest } from '@/types/instrument';
import { useMessage } from '@/hooks/useMessage';
import { FileValue } from '@/components/FileUpload';
import { OrderType } from '@/types/instrument';
import { BasicInfoFormRef } from './components/BasicInfoForm';
import { ReservationSettingsRef } from './components/ReservationSettings';
import { TimeScheduleRef } from './components/TimeSchedule';

type PageMode = 'create' | 'edit' | 'view';

// 辅助函数：将 FileValue 对象转换为 fileKey 字符串
const extractFileKey = (value: string | FileValue | undefined): string | undefined => {
  if (!value) return undefined;
  if (typeof value === 'string') return value;
  return value.fileKey;
};

// 辅助函数：处理提交数据，将 FileValue 对象转换为 fileKey
const processSubmitData = (data: any) => {
  return {
    ...data,
    picImg: extractFileKey(data.picImg),
    qrCodeImg: extractFileKey(data.qrCodeImg),
    curatorImg: extractFileKey(data.curatorImg),
  };
};

const InstrumentManagePage: React.FC = () => {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('basic');
  const [instrumentData, setInstrumentData] = useState<InstrumentInfo | null>(null);
  const [formData, setFormData] = useState<Partial<InstrumentCreateRequest>>({});
  const [currentMinDuration, setCurrentMinDuration] = useState<number>(30);
  const message = useMessage();
  
  // 子组件 refs
  const basicInfoFormRef = useRef<BasicInfoFormRef>(null);
  const reservationSettingsRef = useRef<ReservationSettingsRef>(null);
  const timeScheduleRef = useRef<TimeScheduleRef>(null);
  
  // 获取页面模式和ID
  const id = searchParams.get('id');
  const mode: PageMode = id ? (searchParams.get('mode') as PageMode || 'view') : 'create';
  
  // 加载仪器数据
  useEffect(() => {
    const loadInstrumentData = async () => {
      if (id && mode !== 'create') {
        setLoading(true);
        try {
          const data = await instrumentApi.getInstrumentDetail(parseInt(id));
          setInstrumentData(data);
          
          // 转换数据格式用于表单回显
          const formValues: Partial<InstrumentCreateRequest> = {
            name: data.name,
            categoryId:  data.categoryId,
            model: data.model,
            description: data.description,
            // 组装图片数据为 FileValue 对象
            picImg: data.picImg && data.picImgUrl ? {
              fileKey: data.picImg,
              fileUrl: data.picImgUrl
            } : undefined,
            qrCodeImg: data.qrCodeImg && data.qrCodeImgUrl ? {
              fileKey: data.qrCodeImg,
              fileUrl: data.qrCodeImgUrl
            } : undefined,
            curatorImg: data.curatorImg && data.curatorImgUrl ? {
              fileKey: data.curatorImg,
              fileUrl: data.curatorImgUrl
            } : undefined,
            introduction: data.introduction,
            curatorUserIds: data.curatorUserIds,
            operatorUserIds: data.operatorUserIds,
            curatorIntroduction: data.curatorIntroduction,
            detailIntroduction: data.detailIntroduction,
            // 预约设置相关字段
            appointForm: data.appointForm,
            orderTypes: data.orderTypes as OrderType,
            deliveryTime: data.deliveryTime,
            trainFeeMethod: data.trainFeeMethod,
            trainFeeUnit: data.trainFeeUnit,
            trainFee: data.trainFee,
            feeMethod: data.feeMethod,
            feeUnit: data.feeUnit,
            price: data.price,
            leadTime: data.leadTime,
            minDuration: data.minDuration,
            // 邮寄地址相关字段
            consignee: data.consignee,
            phone: data.phone,
            provinceCode: data.provinceCode,
            cityCode: data.cityCode,
            districtCode: data.districtCode,
            address: data.address,
            // 这些字段暂时设为空数组，后续可能需要额外的API调用获取
            consumables: data.consumables,
            incrementServices: data.incrementServices,
            instrumentSchedules: data.instrumentSchedules,
            instrumentScheduleSpecificDates: data.instrumentScheduleSpecificDates,
          };
          
          setFormData(formValues);
          setCurrentMinDuration(data.minDuration || 30);
          form.setFieldsValue(formValues);
        } catch (error) {
          console.error('加载仪器数据失败:', error);
          message.error('加载仪器数据失败');
        } finally {
          setLoading(false);
        }
      }
    };

    loadInstrumentData();
  }, [id, mode, form, message]);

  // 页面标题映射
  const pageTitleMap = {
    create: '新增仪器',
    edit: '编辑仪器',
    view: '查看仪器'
  };

  // 取消操作
  const handleCancel = () => {
    router.back();
  };
  
  // 保存草稿
  const handleSaveDraft =useCallback( async  () => {
    try {
      // 检查组件是否已经准备好
      if (!basicInfoFormRef.current || !reservationSettingsRef.current || !timeScheduleRef.current) {
        message.error('组件还未完全加载，请稍后再试');
        return;
      }

      // 从各个子组件收集数据
      const basicInfoValues = basicInfoFormRef.current?.getFormData?.() || {};
      const reservationValues = reservationSettingsRef.current?.getFormData?.() || {};
      const timeScheduleValues = timeScheduleRef.current?.getFormData?.() || {};



      const rawData = {
        ...basicInfoValues,
        ...reservationValues,
        ...timeScheduleValues,
        categoryId: Array.isArray(basicInfoValues.categoryId) ? basicInfoValues.categoryId[basicInfoValues.categoryId.length - 1] : basicInfoValues.categoryId,
      };

      // 处理图片数据，将 FileValue 对象转换为 fileKey
      const submitData = processSubmitData(rawData);

      console.log('合并后的原始数据:', rawData);
      console.log('最终提交数据:', submitData);
      console.log('提交数据字段数量:', Object.keys(submitData).length);
      if (mode === 'create') {
        await instrumentApi.stashInstrument(submitData as InstrumentCreateRequest);
        message.success('草稿保存成功');
      } else {
        // 编辑模式下的暂存逻辑
        await instrumentApi.updateInstrument({
          ...submitData,
          id: parseInt(id!)
        } as InstrumentCreateRequest & { id: number });
        message.success('草稿保存成功');
      }
    } catch (error) {
      console.error('保存草稿失败:', error);
      message.error('保存草稿失败');
    }
  },[mode,message]);

  // 切换到编辑模式
  const handleEdit = () => {
    const newUrl = `/instruments/create?id=${id}&mode=edit`;
    router.push(newUrl);
  };

  // 获取操作按钮
  const getActionButtons = () => {
    if (mode === 'view') {
      return (
        <Space size="middle">
          <Button onClick={handleCancel}>
            返回
          </Button>
          <Button 
            type="primary" 
            icon={<EditOutlined />}
            onClick={handleEdit}
            style={{ backgroundColor: '#69cac3', borderColor: '#69cac3' }}
          >
            编辑
          </Button>
        </Space>
      );
    }

    return (
      <Space size="middle">
        <Button onClick={handleCancel}>
          取消
        </Button>
        {mode === 'create' || mode === 'edit' ? (
          <Button onClick={handleSaveDraft}>
            暂存保存
          </Button>
        ) : null}
        <Button 
          type="primary" 
          loading={loading}
          icon={<SaveOutlined />}
          onClick={async () => {
            setLoading(true);
            try {
              // 从各个子组件收集数据
              const basicInfoValues = basicInfoFormRef.current?.getFormData?.() || {};
              const reservationValues = reservationSettingsRef.current?.getFormData?.() || {};
              const timeScheduleValues = timeScheduleRef.current?.getFormData?.() || {};

              const rawData = {
                ...basicInfoValues,
                ...reservationValues,
                ...timeScheduleValues,
                categoryId: Array.isArray(basicInfoValues.categoryId) ? basicInfoValues.categoryId[basicInfoValues.categoryId.length - 1] : basicInfoValues.categoryId,
              };

              // 处理图片数据，将 FileValue 对象转换为 fileKey
              const submitData = processSubmitData(rawData);

              console.log('最终提交数据:', submitData);
              if (mode === 'create') {
                await instrumentApi.createInstrument(submitData as InstrumentCreateRequest);
                message.success('仪器创建成功');
              } else if (mode === 'edit') {
                await instrumentApi.updateInstrument({
                  ...submitData,
                  id: parseInt(id!)
                } as InstrumentCreateRequest & { id: number });
                message.success('仪器更新成功');
              }
              // router.push('/instruments');
            } catch (error) {
              console.error(`${mode === 'create' ? '创建' : '更新'}失败:`, error);
              message.error(`${mode === 'create' ? '创建' : '更新'}失败，请重试`);
            } finally {
              setLoading(false);
            }
          }}
          style={{ backgroundColor: '#69cac3', borderColor: '#69cac3' }}
        >
          {mode === 'create' ? '创建' : '保存'}
        </Button>
      </Space>
    );
  };

  const tabItems = [
    {
      key: 'basic',
      label: '基本信息',
    },
    {
      key: 'reservation',
      label: '预约设置',
    },
    {
      key: 'schedule',
      label: '时间排期',
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      {/* 页面标题 */}
      <div style={{ marginBottom: '24px' }}>
        <Space>
          <Button 
            type="text" 
            icon={<ArrowLeftOutlined />} 
            onClick={() => router.back()}
          >
            返回
          </Button>
          <span style={{ fontSize: '20px', fontWeight: 'bold' }}>
            管理后台 / 仪器管理 / {pageTitleMap[mode]}
          </span>
          {mode === 'view' && instrumentData?.name && (
            <span style={{ fontSize: '16px', color: '#666' }}>
              - {instrumentData.name}
            </span>
          )}
        </Space>
      </div>

      {/* 主要内容 */}
      <Card >
        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          items={tabItems}
        />

        {/* 渲染所有组件，但只显示当前激活的 */}
        <div style={{ display: activeTab === 'basic' ? 'block' : 'none' }}>
          <BasicInfoForm
            ref={basicInfoFormRef}
            form={form}
            mode={mode}
            initialValues={formData}
          />
        </div>

        <div style={{ display: activeTab === 'reservation' ? 'block' : 'none' }}>
          <ReservationSettings
            ref={reservationSettingsRef}
            mode={mode}
            initialValues={formData}
            onMinDurationChange={setCurrentMinDuration}
          />
        </div>

        <div style={{ display: activeTab === 'schedule' ? 'block' : 'none' }}>
          <TimeSchedule
            ref={timeScheduleRef}
            mode={mode}
            initialValues={formData}
            minDuration={currentMinDuration}
          />
        </div>

        {/* 底部操作按钮 */}
        <div style={{ 
          marginTop: '32px', 
          textAlign: 'center',
          borderTop: '1px solid #f0f0f0',
          paddingTop: '24px'
        }}>
          {getActionButtons()}
        </div>
      </Card>
    </div>
  );
};

export default InstrumentManagePage; 